<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/5/26 0026
 * Time: 16:50
 */

namespace classes;

class Verify{
    public static function check($input, $name = 'verify'){
        $verify = session($name);
        self::clear($name);
        return $verify === strtoupper($input);
    }

    private static function clear($name){
        session($name, null);
    }

    public static function build($char_count = 4, $width = 80, $height = 24, $name='verify'){
        if(!in_array($name, array('verify_login', 'verify_feedback', 'verify_recharge', 'verify_tender', 'verify_answer', 'verify'))) return;
        // 干扰线宽度为图片宽度的5%
        $average = round($width / $char_count) ;
        $min_reference = min($height, $average) ;
        $font = __DIR__.'/../../resource/ariblk.ttf' ;
        $string_map = 'ABCDEFGHIJKLMNPQRSTUVWXYZ123456789' ;
        $map_length = strlen($string_map) ;
        $char = array();
        for($i=0; $i<$char_count; $i++)$char[] = substr($string_map, mt_rand(0, $map_length - 1), 1) ;

        // 设置session
        session($name, implode('', $char)) ;

        $image = imagecreate($width, $height);
        imagefill($image, 0, 0, imagecolortransparent($image, imagecolorallocate($image, 0xff, 0xff, 0xff)));
        $color = imagecolorallocate($image, 0x53, 0x68, 0xbd);
        // 干扰线y坐标的初始范围
        for($i=0; $i<$char_count; $i++){
            $fontsize = mt_rand($min_reference - 6, $min_reference - 3) ;
            $angle = mt_rand(-10,10) ;
            $x = $width/$char_count * $i + mt_rand(0, $average - $fontsize) ;
            $y = (int) mt_rand($fontsize - 2,$height - 2) ;
            imagettftext($image, $fontsize, $angle, $x, $y, $color, $font, $char[$i]);
        }
        header('content-type:image/png') ;
        imagepng($image);
        imagedestroy($image);
        die;
    }
}